package cn.klaw.config;

import com.baomidou.lock.LockTemplate;
import cn.klaw.consts.ProjectEventConst;
import cn.klaw.event.ProjectEventListenerAnnotationBeanPostProcessor;
import cn.klaw.event.ProjectEventProccess;
import cn.klaw.event.ProjectEventSender;
import cn.klaw.util.PublishEventUtil;
import cn.klaw.event.*;
import cn.klaw.handler.ProjectEventRedisMessageHandler;
import cn.klaw.handler.ProjectEventRedisSender;
import cn.klaw.properties.EventProperty;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;

@Configuration(proxyBeanMethods = false)
public class ProjectEventAutoConfiguration {



    @Bean
    @ConfigurationProperties(prefix = EventProperty.PREFIX)
    public EventProperty getEventProperties(){
        return new EventProperty();
    }


    @Bean
    public ProjectEventListenerAnnotationBeanPostProcessor getProjectEventListenerAnnotationBeanPostProcessor(){
        return new ProjectEventListenerAnnotationBeanPostProcessor();
    }

    @Bean
    public ProjectEventProccess getProjectEventProccess(LockTemplate lockTemplate, ConfigValueUtil configValueUtil){
        return new ProjectEventProccess(lockTemplate, configValueUtil);
    }

    @Bean
    @ConditionalOnProperty(prefix = "event", name = "event-publish-type", havingValue = ProjectEventConst.EVENT_PUBLISH_TYPE_REDIS, matchIfMissing = true)
    public ProjectEventRedisMessageHandler getProjectEventRedisMessageHandler(RedisMessageListenerContainer container, EventProperty eventProperty){
        return new ProjectEventRedisMessageHandler(container, eventProperty);
    }

    /**
     * 自定义事件发布渠道为QUEUE
     */
    @Bean
    @ConditionalOnProperty(prefix = "event", name = "event-publish-type", havingValue = ProjectEventConst.EVENT_PUBLISH_TYPE_REDIS, matchIfMissing = true)
    public ProjectEventRedisSender getProjectEventRedisSender(RedisTemplate redisTemplate, EventProperty eventProperty){
        return new ProjectEventRedisSender(redisTemplate, eventProperty);
    }


    @Bean
    public PublishEventUtil getPublishEventUtil(@Autowired(required = false) ProjectEventSender eventSender){
        return new PublishEventUtil(eventSender);
    }

}
